<template>
  <div class="assembly-work-order-container">
    <!-- 装配工单主表 -->
    <div class="assembly-work-order-section">
      <div class="section-header">
        <h3>装配工单</h3>
      </div>
      
      <!-- 搜索和操作栏 -->
      <div class="search-action-bar">
        <div class="search-area">
          <el-input
            v-model="searchForm.documentNo"
            placeholder="单据编号"
            clearable
            style="width: 200px; margin-right: 10px;"
          />
          <el-input
            v-model="searchForm.workOrderCount"
            placeholder="工单数"
            clearable
            style="width: 120px; margin-right: 10px;"
          />
          <el-input
            v-model="searchForm.finishedWorkOrders"
            placeholder="已结束工单"
            clearable
            style="width: 120px; margin-right: 10px;"
          />
          <el-button type="primary" @click="handleSearch">Q查询</el-button>
          <el-button type="info" @click="handleReset">重置</el-button>
        </div>
        
        <div class="action-buttons">
          <el-button type="success" @click="handleAdd">+新建</el-button>
        </div>
      </div>

      <!-- 装配工单表格 -->
      <div class="table-container">
        <el-table
          :data="assemblyWorkOrderList"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          v-loading="loading"
          style="width: 100%; height: 100%"
          border
          stripe
          highlight-current-row
          height="100%"
        >
          <el-table-column type="index" width="60" align="center" />
          <el-table-column type="selection" width="50" />
          <el-table-column prop="documentNo" label="单据编号" sortable width="220" />
          <el-table-column prop="workOrderCount" label="工单数" width="100" />
          <el-table-column prop="finishedWorkOrders" label="已结束工单" width="120" />
          <el-table-column prop="documentProgress" label="单据进度" width="150">
            <template #default="scope">
              <el-progress 
                :percentage="parseInt(scope.row.documentProgress) || 0" 
                :stroke-width="8"
                :show-text="true"
              />
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="150" />
          <el-table-column prop="createTime" label="创建时间" sortable width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="modifier" label="修改人" width="120" />
          <el-table-column prop="modifyTime" label="修改时间" sortable width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.modifyTime) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.pageIndex"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 装配工单产品明细 -->
    <div class="product-detail-section">
      <div class="section-header">
        <h3>装配工单-产品明细 {{ currentWorkOrderId ? `(工单ID: ${currentWorkOrderId})` : '(全部产品明细)' }}</h3>
        <div class="section-actions">
          <el-button type="info" size="small" @click="handleShowAllProducts">显示全部</el-button>
        </div>
      </div>
      
      <!-- 产品明细表格 -->
      <div class="table-container">
        <el-table
          :data="productDetailList"
          v-loading="productLoading"
          style="width: 100%; height: 100%"
          border
          stripe
          height="100%"
        >
          <el-table-column type="index" width="60" align="center" />
          <el-table-column prop="levelNumber" label="层级编号" sortable width="100" />
          <el-table-column prop="productCode" label="*产品编号" sortable width="220" />
          <el-table-column prop="productName" label="*产品名称" sortable width="180" />
          <el-table-column prop="productSpec" label="产品规格" width="150" />
          <el-table-column prop="workOrderNo" label="工单编号" width="220" />
          <el-table-column prop="quantity" label="*数量" sortable width="100" />
          <el-table-column prop="completedQty" label="完成数" width="100" />
          <el-table-column prop="createTime" label="创建时间" sortable width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="创建人" width="120" />
          <el-table-column prop="modifier" label="修改人" width="120" />
          <el-table-column prop="modifyTime" label="修改时间" sortable width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.modifyTime) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1200px"
      :before-close="handleDialogClose"
      top="5vh"
    >
      <!-- 基本信息 -->
      <div class="dialog-content">
        <div class="basic-info-section">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单据编号:" label-width="100px">
                <el-input 
                  v-model="formData.documentNo" 
                  placeholder="请输入单据编号，留空将自动生成"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注:" label-width="100px">
                <el-input 
                  v-model="formData.remark" 
                  placeholder="备注"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 提示信息 -->
          <div class="hint-message">
            <el-icon color="#E6A23C"><Warning /></el-icon>
            <span>点击【数量】【单位数量】可以对数量直接进行修改</span>
          </div>
        </div>

        <!-- 产品明细表格 -->
        <div class="product-detail-section">
          <div class="section-title">
            <h4>装配工单-产品明细</h4>
          </div>
          
          <!-- 操作按钮 -->
          <div class="table-actions">
            <el-button type="primary" size="small" @click="handleSelectProduct">
              <el-icon><Plus /></el-icon>选择产品
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteRows">
              <el-icon><Delete /></el-icon>删除行
            </el-button>
            <el-button type="info" size="small" @click="handleImport">
              <el-icon><Upload /></el-icon>导入
            </el-button>
            <el-button type="warning" size="small" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>

          <!-- 产品明细表格 -->
          <el-table
            :data="dialogProductList"
            @selection-change="handleDialogSelectionChange"
            style="width: 100%"
            border
            stripe
            height="400"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column prop="levelNumber" label="层级编号" sortable width="100" />
            <el-table-column prop="productCode" label="*产品编号" sortable width="220" />
            <el-table-column prop="productName" label="*产品名称" sortable width="180" />
            <el-table-column prop="productSpec" label="产品规格" width="150" />
            <el-table-column prop="workOrderNo" label="工单编号" width="220" />
            <el-table-column prop="quantity" label="*数量" sortable width="100" />
            <el-table-column prop="completedQty" label="完成数" width="100" />
            <el-table-column prop="createTime" label="创建时间" sortable width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="creator" label="创建人" width="120" />
            <el-table-column prop="modifier" label="修改人" width="120" />
            <el-table-column prop="modifyTime" label="修改时间" sortable width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.modifyTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="scope">
                <el-dropdown>
                  <el-button type="text" size="small">
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleEditRow(scope.row)">编辑</el-dropdown-item>
                      <el-dropdown-item @click="handleDeleteRow(scope.row)" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="table-pagination">
            <el-pagination
              :current-page="dialogPagination.pageIndex"
              :page-size="dialogPagination.pageSize"
              :page-sizes="[50, 100, 200]"
              :total="dialogPagination.totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleDialogSizeChange"
              @current-change="handleDialogCurrentChange"
            />
          </div>
        </div>
      </div>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="handleSave">
            <el-icon><Check /></el-icon>保存
          </el-button>
          <el-button type="primary" @click="handleDialogClose">
            <el-icon><Close /></el-icon>关闭
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择产品对话框 -->
    <el-dialog
      v-model="selectProductDialogVisible"
      title="选择产品"
      width="1000px"
      :before-close="handleSelectProductDialogClose"
      top="5vh"
    >
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产品编码:" label-width="80px">
              <el-input 
                v-model="selectProductSearchForm.productCode" 
                placeholder="请输入产品编码"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名称:" label-width="80px">
              <el-input 
                v-model="selectProductSearchForm.productName" 
                placeholder="请输入产品名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品规格:" label-width="80px">
              <el-input 
                v-model="selectProductSearchForm.productSpec" 
                placeholder="请输入产品规格"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-button type="primary" @click="handleSelectProductSearch">搜索</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 产品列表表格 -->
      <el-table
        :data="selectProductList"
        @selection-change="handleSelectProductSelectionChange"
        style="width: 100%"
        border
        stripe
        height="400"
        v-loading="selectProductLoading"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="productCode" label="产品编号" sortable width="200" />
        <el-table-column prop="productName" label="产品名称" sortable width="150" />
        <el-table-column prop="productSpec" label="产品规格" width="120" />
        <el-table-column prop="unit" label="库存单位" width="100" />
        <el-table-column prop="stockQty" label="库存数量" width="100" />
        <el-table-column prop="price" label="单价" width="100" />
        <el-table-column prop="createTime" label="创建时间" sortable width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="select-product-pagination">
        <el-pagination
          :current-page="selectProductPagination.pageIndex"
          :page-size="selectProductPagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="selectProductPagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSelectProductSizeChange"
          @current-change="handleSelectProductCurrentChange"
        />
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleAddSelectedProducts">
            添加选择的数据
          </el-button>
          <el-button @click="handleSelectProductDialogClose">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { 
  Warning, 
  Plus, 
  Delete, 
  Upload, 
  Refresh, 
  MoreFilled, 
  Check, 
  Close 
} from '@element-plus/icons-vue'
import {
  getAssemblyWorkOrders,
  getAssemblyWorkOrderDetails,
  createAssemblyWorkOrder,
  createAssemblyWorkOrderWithDetails,
  batchCreateAssemblyWorkOrderDetails,
  updateAssemblyWorkOrder,
  deleteAssemblyWorkOrder,
  batchDeleteAssemblyWorkOrders,
  exportAssemblyWorkOrderTemplate,
  exportAssemblyWorkOrders,
  type AssemblyWorkOrder,
  type AssemblyWorkOrderDetail,
  type SearchParams,
  type CreateAssemblyWorkOrderDetail,
  type CreateAssemblyWorkOrderWithDetails
} from '@/api/assemblyWorkOrder'
import { MES_SMH_ApiHost } from '@/utils/Interceptors'

// 响应式数据
const loading = ref(false)
const productLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()
const selectedRows = ref<AssemblyWorkOrder[]>([])
const currentWorkOrderId = ref<number | null>(null)

// 列表数据
const assemblyWorkOrderList = ref<AssemblyWorkOrder[]>([])
const productDetailList = ref<AssemblyWorkOrderDetail[]>([])

// 对话框相关数据
const dialogProductList = ref<AssemblyWorkOrderDetail[]>([])
const dialogSelectedRows = ref<AssemblyWorkOrderDetail[]>([])
const dialogPagination = reactive({
  pageIndex: 1,
  pageSize: 100,
  totalCount: 0
})

// 选择产品对话框相关数据
const selectProductDialogVisible = ref(false)
const selectProductLoading = ref(false)
const selectProductList = ref<any[]>([])
const selectProductSelectedRows = ref<any[]>([])
const selectProductSearchForm = reactive({
  productCode: '',
  productName: '',
  productSpec: ''
})
const selectProductPagination = reactive({
  pageIndex: 1,
  pageSize: 30,
  totalCount: 0
})

// 搜索表单 - 根据Swagger文档更新字段名
const searchForm = reactive<SearchParams>({
  documentNo: '',
  workOrderCount: undefined,
  finishedWorkOrders: undefined
})

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 30,
  totalCount: 0
})

// 表单数据 - 根据Swagger文档更新字段名
const formData = reactive<Partial<AssemblyWorkOrder>>({
  documentNo: '',
  workOrderCount: 0,
  finishedWorkOrders: 0,
  documentProgress: '0',
  remark: ''
})

// 表单验证规则
const formRules: FormRules = {
  documentNo: [
    { required: true, message: '请输入单据编号', trigger: 'blur' }
  ],
  workOrderCount: [
    { required: true, message: '请输入工单数', trigger: 'blur' }
  ]
}

// 获取装配工单列表 - 使用真实API
const fetchAssemblyWorkOrders = async () => {
  try {
    loading.value = true
    
    const params: SearchParams = {
      ...searchForm,
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    }
    
    const response = await getAssemblyWorkOrders(params)
    if (response.data.code === 200) {
      assemblyWorkOrderList.value = response.data.data.pageData
      pagination.totalCount = response.data.data.totalCount
    } else {
      ElMessage.error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取装配工单列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 获取产品明细
const fetchProductDetails = async (workOrderId: number) => {
  try {
    productLoading.value = true
    
    const response = await getAssemblyWorkOrderDetails(workOrderId)
    if (response.data.code === 200) {
      // 处理数据，为空的层级编号生成临时编号
      const processedData = response.data.data.map((item, index) => ({
        ...item,
        levelNumber: item.levelNumber || String(index + 1)
      }))
      productDetailList.value = processedData
    } else {
      ElMessage.error(response.data.msg || '获取产品明细失败')
    }
  } catch (error) {
    console.error('获取产品明细失败:', error)
    ElMessage.error('获取产品明细失败')
  } finally {
    productLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1
  fetchAssemblyWorkOrders()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    documentNo: '',
    workOrderCount: undefined,
    finishedWorkOrders: undefined
  })
  pagination.pageIndex = 1
  fetchAssemblyWorkOrders()
}

// 新建
const handleAdd = () => {
  dialogTitle.value = '装配工单(新建)'
  Object.assign(formData, {
    documentNo: '',
    workOrderCount: 0,
    finishedWorkOrders: 0,
    documentProgress: '0',
    remark: ''
  })
  
  // 产品明细表格默认为空
  dialogProductList.value = []
  dialogPagination.totalCount = 0
  dialogVisible.value = true
}

// 表格选择变化
const handleSelectionChange = (selection: AssemblyWorkOrder[]) => {
  selectedRows.value = selection
}

// 行点击事件
const handleRowClick = (row: AssemblyWorkOrder) => {
  currentWorkOrderId.value = row.assemblyWorkOrderId
  if (row.assemblyWorkOrderId) {
    fetchProductDetails(row.assemblyWorkOrderId)
  }
}

// 显示全部产品
const handleShowAllProducts = () => {
  currentWorkOrderId.value = null
  // 清空产品明细列表，而不是调用API
  productDetailList.value = []
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchAssemblyWorkOrders()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchAssemblyWorkOrders()
}

// 对话框关闭
const handleDialogClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    const response = await createAssemblyWorkOrder(formData)
    if (response.data.code === 200) {
      ElMessage.success('创建成功')
      dialogVisible.value = false
      fetchAssemblyWorkOrders()
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

// 对话框相关函数
const handleSelectProduct = () => {
  selectProductDialogVisible.value = true
  fetchSelectProductList()
}

// 选择产品对话框相关函数
const fetchSelectProductList = async () => {
  try {
    selectProductLoading.value = true
    
    // 调用后端API获取产品数据
    const response = await MES_SMH_ApiHost.get('/api/AssemblyWorkOrder/GetAllProductDetailsForSelection', {
      params: {
        productCode: selectProductSearchForm.productCode || undefined,
        productName: selectProductSearchForm.productName || undefined,
        productSpec: selectProductSearchForm.productSpec || undefined,
        pageIndex: selectProductPagination.pageIndex,
        pageSize: selectProductPagination.pageSize
      }
    })
    
    if (response.data.code === 200) {
      selectProductList.value = response.data.data.pageData
      selectProductPagination.totalCount = response.data.data.totalCount
    } else {
      ElMessage.error(response.data.msg || '获取产品列表失败')
    }
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
  } finally {
    selectProductLoading.value = false
  }
}

const handleSelectProductSearch = () => {
  selectProductPagination.pageIndex = 1
  fetchSelectProductList()
}

const handleSelectProductSelectionChange = (selection: any[]) => {
  selectProductSelectedRows.value = selection
}

const handleSelectProductSizeChange = (size: number) => {
  selectProductPagination.pageSize = size
  selectProductPagination.pageIndex = 1
  fetchSelectProductList()
}

const handleSelectProductCurrentChange = (page: number) => {
  selectProductPagination.pageIndex = page
  fetchSelectProductList()
}

const handleAddSelectedProducts = () => {
  if (selectProductSelectedRows.value.length === 0) {
    ElMessage.warning('请选择要添加的产品')
    return
  }
  
  // 将选中的产品添加到对话框的产品列表中
  const newProducts = selectProductSelectedRows.value.map((product, index) => ({
    assemblyWorkOrderDetailId: Date.now() + index, // 临时ID
    assemblyWorkOrderId: 0,
    levelNumber: String(dialogProductList.value.length + index + 1),
    productCode: product.productCode,
    productName: product.productName,
    productSpec: product.productSpec,
    workOrderNo: '',
    quantity: 1,
    completedQty: 0,
    createTime: new Date().toISOString(),
    creator: '当前用户',
    modifier: '',
    modifyTime: '',
    unit: product.unit,
    stockQty: product.stockQty,
    price: product.price
  }))
  
  dialogProductList.value.push(...newProducts)
  dialogPagination.totalCount = dialogProductList.value.length
  
  ElMessage.success(`成功添加 ${newProducts.length} 个产品`)
  selectProductDialogVisible.value = false
}

const handleSelectProductDialogClose = () => {
  selectProductDialogVisible.value = false
  // 重置搜索表单
  Object.assign(selectProductSearchForm, {
    productCode: '',
    productName: '',
    productSpec: ''
  })
  selectProductSelectedRows.value = []
}

const handleDeleteRows = () => {
  if (dialogSelectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的行')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${dialogSelectedRows.value.length} 行吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const selectedIds = dialogSelectedRows.value.map(row => row.assemblyWorkOrderDetailId)
    dialogProductList.value = dialogProductList.value.filter(
      item => !selectedIds.includes(item.assemblyWorkOrderDetailId)
    )
    ElMessage.success('删除成功')
  })
}

const handleImport = () => {
  ElMessage.info('导入功能待实现')
}

const handleRefresh = () => {
  // 刷新对话框中的产品列表
  ElMessage.success('刷新成功')
}

const handleDialogSelectionChange = (selection: AssemblyWorkOrderDetail[]) => {
  dialogSelectedRows.value = selection
}

const handleEditRow = (row: AssemblyWorkOrderDetail) => {
  ElMessage.info(`编辑产品: ${row.productName}`)
}

const handleDeleteRow = (row: AssemblyWorkOrderDetail) => {
  ElMessageBox.confirm(
    `确定要删除产品 "${row.productName}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = dialogProductList.value.findIndex(
      item => item.assemblyWorkOrderDetailId === row.assemblyWorkOrderDetailId
    )
    if (index > -1) {
      dialogProductList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}

const handleDialogSizeChange = (size: number) => {
  dialogPagination.pageSize = size
  dialogPagination.pageIndex = 1
  // 这里可以重新加载对话框中的产品数据
}

const handleDialogCurrentChange = (page: number) => {
  dialogPagination.pageIndex = page
  // 这里可以重新加载对话框中的产品数据
}

const handleSave = async () => {
  try {
    // 如果单据编号为空，自动生成
    if (!formData.documentNo || formData.documentNo.trim() === '') {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hour = String(now.getHours()).padStart(2, '0')
      const minute = String(now.getMinutes()).padStart(2, '0')
      const second = String(now.getSeconds()).padStart(2, '0')
      const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
      
      formData.documentNo = `ZPGD${year}${month}${day}${hour}${minute}${second}${random}`
    }
    
    // 准备产品明细数据
    const details: CreateAssemblyWorkOrderDetail[] = dialogProductList.value.map((item, index) => ({
      productCode: item.productCode,
      productName: item.productName,
      productSpec: item.productSpec,
      workOrderNo: item.workOrderNo,
      quantity: item.quantity,
      levelNumber: item.levelNumber,
      completedQty: item.completedQty || 0
    }))
    
    // 准备提交的数据 - 使用CreateWithDetails接口
    const submitData: CreateAssemblyWorkOrderWithDetails = {
      assemblyWorkOrder: {
        documentNo: formData.documentNo,
        workOrderCount: dialogProductList.value.length, // 根据产品明细数量设置工单数
        finishedWorkOrders: 0,
        documentProgress: '0',
        remark: formData.remark || '',
        creator: '当前用户'
      },
      details: details
    }
    
    // 调用创建装配工单（包含明细）的API
    const response = await createAssemblyWorkOrderWithDetails(submitData)
    console.log('API响应:', response) // 添加调试日志
    
    // 检查响应结构
    if (response.data && response.data.code === 200) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      
      // 获取新创建的工单ID
      const newWorkOrderId = response.data.data?.assemblyWorkOrderId
      
      // 刷新工单列表
      await fetchAssemblyWorkOrders()
      
      // 如果有新创建的工单ID，自动选中并显示其产品明细
      if (newWorkOrderId) {
        // 等待DOM更新后选中新创建的工单
        await nextTick()
        
        // 查找新创建的工单行并触发点击事件
        const newWorkOrder = assemblyWorkOrderList.value.find(item => item.assemblyWorkOrderId === newWorkOrderId)
        if (newWorkOrder) {
          currentWorkOrderId.value = newWorkOrderId
          await fetchProductDetails(newWorkOrderId)
          
          // 高亮显示新创建的工单行
          ElMessage.success(`已自动选中新创建的工单：${newWorkOrder.documentNo}`)
        }
      }
      
      // 显示成功信息
      if (details.length > 0) {
        ElNotification({
          title: '成功',
          message: `装配工单创建成功，包含 ${details.length} 个产品明细。`,
          type: 'success',
          duration: 3000
        })
      }
    } else {
      console.error('保存失败，响应:', response)
      ElMessage.error(response.data?.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 初始化数据
onMounted(() => {
  fetchAssemblyWorkOrders()
  // 移除页面初始化时的产品明细调用，只在用户点击行时才获取
  // fetchProductDetails()
})
</script>

<style scoped>
.assembly-work-order-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.assembly-work-order-section {
  background-color: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 400px;
  max-height: calc(100vh - 200px);
}

.product-detail-section {
  background-color: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  min-height: 300px;
  max-height: calc(100vh - 600px);
}

.section-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.section-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.search-action-bar {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.table-container {
  padding: 0 20px 20px;
  flex: 1;
  overflow: hidden;
}

.pagination-container {
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: center;
}

:deep(.el-table) {
  border-radius: 4px;
}

/* 表格滚动条样式 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-progress) {
  margin: 0;
}

:deep(.el-progress__text) {
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .search-action-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-area,
  .action-buttons {
    justify-content: center;
  }
}

/* 对话框样式 */
.dialog-content {
  max-height: 70vh;
  overflow-y: auto;
}

.basic-info-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.hint-message {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 15px;
  padding: 10px;
  background-color: #fdf6ec;
  border: 1px solid #f5dab1;
  border-radius: 4px;
  color: #e6a23c;
  font-size: 14px;
}

.product-detail-section {
  margin-top: 20px;
}

.section-title {
  margin-bottom: 15px;
}

.section-title h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.table-actions {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.table-pagination {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 对话框表格样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e4e7ed;
  padding: 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #e4e7ed;
  padding: 15px 20px;
}

/* 选择产品对话框样式 */
.search-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.select-product-pagination {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}
</style>
